<template>
  <div class="binding-management">
    <!-- 搜索区域 -->
    <div class="query-section">
        <el-card shadow="never" class="query-card">
        <el-form :model="queryParams" ref="queryFormRef" class="query-form" label-width="100px">
            <el-row :gutter="20">
            <!-- 家属姓名 -->
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <el-form-item label="家属姓名">
                <el-input
                    v-model.trim="queryParams.familyName"
                    placeholder="请输入家属姓名"
                    clearable
                    @keyup.enter="handleQuery"
                />
                </el-form-item>
            </el-col>

            <!-- 老人姓名 -->
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <el-form-item label="老人姓名">
                <el-input
                    v-model.trim="queryParams.elderlyName"
                    placeholder="请输入老人姓名"
                    clearable
                    @keyup.enter="handleQuery"
                />
                </el-form-item>
            </el-col>

            <!-- 操作按钮 -->
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <el-form-item label-width="0" class="action-buttons-wrapper">
                    <el-button type="primary" @click="handleQuery" :loading="loading" icon="Search">查询</el-button>
                    <el-button @click="resetQuery" icon="Refresh">重置</el-button>
                </el-form-item>
            </el-col>
            </el-row>
        </el-form>
        </el-card>
    </div>

    <!-- 操作按钮 -->
    <div class="action-section">
        <el-card shadow="never" class="action-card">
            <div class="action-bar">
                <div class="action-left">
                    <!-- 刷新按钮 -->
                    <el-button type="info" icon="Refresh" @click="handleRefresh" :loading="loading">刷新</el-button>
                    <!-- 批量删除按钮 -->
                    <el-button type="danger" icon="Delete" @click="handleBatchDelete" :disabled="!selectedBindings.length">批量删除</el-button>
                </div>
                <div class="total-info">
                    共 <strong class="total-count">{{ totalItems }}</strong> 条记录
                </div>
            </div>
        </el-card>
    </div>

    <!-- 绑定关系列表 -->
    <div class="content-section" ref="contentSectionRef">
        <el-card shadow="never" class="content-card">
            <div class="desktop-table">
                <el-table
                    :data="bindings"
                    v-loading="loading"
                    style="width: 100%"
                    border
                    stripe
                    @selection-change="handleSelectionChange"
                    v-model:selection="selectedBindings"
                >
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column label="家属姓名" prop="familyName" align="center"></el-table-column>
                    <el-table-column label="家属电话" prop="familyPhone" align="center"></el-table-column>
                    <el-table-column label="老人姓名" prop="elderlyName" align="center"></el-table-column>
                    <el-table-column label="老人身份证" prop="elderlyIdCard" align="center"></el-table-column>
                    <el-table-column label="关系" prop="familyRelationship" align="center"></el-table-column>
                    <el-table-column label="状态" prop="status" align="center">
                        <template #default="{ row }">
                            <el-tag :type="getCheckInStatusTagType(row.status)" effect="light">
                                {{ row.status }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="180">
                        <template #default="{ row }">
                            <div class="table-actions">
                            <el-button
                                v-if="row.status === '待审批'"
                                text
                                type="primary"
                                size="small"
                                icon="Check"
                                @click="approveBinding(row.id)"
                            >
                                审批
                            </el-button>
                            <el-button
                                text
                                type="danger"
                                size="small"
                                icon="Delete"
                                @click="deleteBinding(row.id)"
                            >
                                删除
                            </el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-card>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
        <el-pagination
        v-if="totalItems > 0"
        @current-change="handlePageChange"
        :page-size="pageSize"
        :current-page="currentPage"
        :total="totalItems"
        layout="total, prev, pager, next, jumper"
        class="pagination-container"
        ></el-pagination>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
import axios from 'axios';
import { Search, Refresh, Plus, Delete, View, Check } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import request from '@/utils/request';

// 存储查询条件
const queryParams = ref({
  familyName: '',
  elderlyName: '',
  page: 1,
  size: 10,
});

// 存储数据
const loading = ref(false);
const bindings = ref([]);
const selectedBindings = ref([]);
const totalItems = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// 模糊查询
const handleQuery = async () => {
  queryParams.value.page = 1;
  await fetchData();
};

// 请求关系数据
const fetchData = async () => {
  loading.value = true;
  try {
    const response = await request.get('/binding', {
      params: {
        familyName: queryParams.value.familyName,
        elderlyName: queryParams.value.elderlyName,
        page: queryParams.value.page,
        size: queryParams.value.size,
      },
    });
    bindings.value = response.records;
    totalItems.value = response.total;
  } catch (error) {
    ElMessage.error("获取数据失败：" + error.message);
  } finally {
    loading.value = false;
  }
};

// 重置查询
const resetQuery = () => {
  queryParams.value.familyName = '';
  queryParams.value.elderlyName = '';
  queryParams.value.page = 1;
  refreshTable();
};

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page;
  refreshTable();
};

// 刷新关系列表
const refreshTable = async () => {
  try {
    const response = await request.get(`/binding/list?page=${currentPage.value}&size=${pageSize.value}`)
    bindings.value = response.records
    totalItems.value = response.total
  } catch (error) {
    console.error('获取老人档案列表失败:', error)
  }
}

// 刷新
const handleRefresh = () => {
  refreshTable();
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedBindings.value.length === 0) {
    ElMessage.warning('请先选择要删除的绑定');
    return;
  }

  // 弹出确认删除的弹框
  ElMessageBox.confirm(
    '您确定要删除选中的档案吗？', // 提示文本
    '警告', // 标题
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      // 用户点击确认时，执行批量删除操作
      try {
        const ids = selectedBindings.value.map(profile => profile.id);  // 提取选中的档案ID
        const response = await request.delete('/binding/admin/batch', { data: ids });  // 批量删除请求
        if (response.status === 200) {
          ElMessage.success('批量删除成功');
          refreshTable();  // 删除后重新获取数据
        }
      } catch (error) {
        console.error('批量删除失败:', error);
        ElMessage.error('批量删除失败，请稍后重试');
      }
    })
    .catch(() => {
      // 用户点击取消时的操作
      ElMessage.info('删除操作已取消');
    });
};

// 删除单个绑定
const deleteBinding = async (id) => {
  // 弹出确认删除的弹框
  ElMessageBox.confirm(
    '您确定要删除此档案吗？', // 提示文本
    '警告', // 标题
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning', // 设置为警告类型
    }
  )
    .then(async () => {
      // 用户点击确认时，执行删除操作
      try {
        const response = await request.delete(`/binding/admin/${id}`);  // 删除请求
        if (response.status === 200) {
          ElMessage.success('删除成功');
          refreshTable();  // 删除后重新获取数据
        }
      } catch (error) {
        console.error('删除失败:', error);
        ElMessage.error('删除失败，请稍后重试');
      }
    })
    .catch(() => {
      // 用户点击取消时的操作
      ElMessage.info('删除操作已取消');
    });
};

// 审批绑定
const approveBinding = async (id) => {
  // 弹出确认框，询问是否通过审批
  ElMessageBox.confirm('您确定要通过此审批吗？', '确认审批', {
    confirmButtonText: '通过',
    cancelButtonText: '拒绝',
    type: 'warning',
  })
    .then(async () => {
      // 用户选择通过审批
      try {
        const response = await request.put(`/binding/${id}/approve`, { approvedByAdminId: 1 }); // 假设 1 是管理员ID
        if (response.status === 200) {
          ElMessage.success('审批通过');
          fetchData(); // 刷新数据
        }
      } catch (error) {
        ElMessage.error('审批失败：' + error.message);
      }
    })
    .catch(async () => {
      // 用户选择拒绝审批
      try {
        const response = await request.put(`/binding/${id}/reject`); // 调用拒绝接口
        if (response.status === 200) {
          ElMessage.success('审批已拒绝');
          fetchData(); // 刷新数据
        }
      } catch (error) {
        ElMessage.error('拒绝审批失败：' + error.message);
      }
    });
};

// 选择变化处理
const handleSelectionChange = (val) => {
  selectedBindings.value = val;
};

// 获取在住状态标签类型
const getCheckInStatusTagType = (status) => {
  switch (status) {
    case '审批通过':
      return 'success';
    case '待审批':
      return 'warning';
    case '已拒绝':
      return 'danger';
    default:
      return 'info';
  }
};

// 初次加载数据
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.binding-management {
  width: 100%;
  height: 100vh;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
}

.query-section,
.action-section {
  flex-shrink: 0;
}

.pagination-section {
  flex-shrink: 0;
}

.content-section {
  flex: 1;
  min-height: 0;
  position: relative;
}

.query-card,
.action-card,
.content-card {
  border: none;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
}

.content-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.content-card ::v-deep .el-card__body {
  flex: 1;
  min-height: 0;
  overflow: hidden;
  padding: 10px;
}

.query-form .action-buttons-wrapper ::v-deep .el-form-item__content {
  display: flex;
  gap: 10px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.total-info {
  font-size: 14px;
  color: #606266;
}

.total-info ::v-deep .total-count {
  color: var(--el-color-primary);
  font-size: 16px;
  font-weight: 600;
  margin: 0 4px;
}

.desktop-table {
  height: 100%;
  width: 100%;
}

.desktop-table {
  display: flex;
  /* 水平居中 */
  overflow-x: auto;
  /* 启用水平滚动条 */
  overflow-y: auto;
  /* 启用垂直滚动条 */
  max-height: 500px;
  /* 限制表格的最大高度 */
}

.desktop-table ::v-deep .el-table {
  max-width: 1200px;
  /* 设置最大宽度，防止过宽 */
  width: 100%;
  /* 占满可用宽度，但不超过max-width */
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
}
</style>
